#include "ThreadObject.h"


namespace Zaf {
namespace Sync {


	
void ThreadObject::Begin(bool waitReady) {

	_ASSERT(m_hasStarted == false);

	if (m_hThread != NULL) {
		CloseHandle(m_hThread);
	}

	if (waitReady == true) {
		m_readyEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
	}

	m_hThread = (HANDLE)_beginthreadex(
		nullptr,
		0,
		ThreadEntry,
		this,
		0,
		nullptr
	);

	if (waitReady == true) {

		WaitForSingleObject(m_readyEvent, INFINITE);
		CloseHandle(m_readyEvent);
		m_readyEvent = NULL;
	}
}



unsigned int __stdcall ThreadObject::ThreadEntry(void* arg) {

	ThreadObject* obj = (ThreadObject*)arg;
	obj->m_hasStarted = true;

	obj->m_hwnd = CreateWindow(
		TEXT("STATIC"),
		nullptr,
		0,
		0,
		0,
		0,
		0,
		HWND_MESSAGE,
		0,
		GetModuleHandle(NULL),
		0
	);

	SetEvent(obj->m_readyEvent);

	obj->DoWork();

	obj->OnThreadEnd();

	return 0;
}



void ThreadObject::DoWork() {

	if (Startup() == false) {
		return;
	}

	MSG msg;
	while (GetMsg(msg) == true) {
		MsgProc(msg.message, msg.wParam, msg.lParam);
	}

	Dispose();
}



void ThreadObject::OnThreadEnd() {

	DestroyWindow(m_hwnd);
	m_hwnd = NULL;

	m_hasStarted = false;
}



}
}